<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 760px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="菜品编号" prop="mealCode">
        <el-input v-model="formData.mealCode" placeholder="请输入菜品编号" disabled />
      </el-form-item>
      <el-form-item label="菜品名称" prop="mealName">
        <el-input v-model="formData.mealName" placeholder="请输入菜品名称" />
      </el-form-item>
      <el-form-item label="所属航空公司" prop="airlineId">
        <el-select v-model="formData.airlineId" placeholder="请选择所属航空公司">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_ID)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜品类型" prop="mealType">
        <el-select v-model="formData.mealType" placeholder="请选择菜品类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PPLAN_MEAL_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <div v-for="(item, index) in formData.mealIngreRespVOS" :key="index" class="flex">
        <!-- 菜品名称 -->
        <el-form-item
          label="配料信息"
          :prop="`mealIngreRespVOS[${index}].productId`"
          :rules="{ required: true, message: '配料不能为空', trigger: 'blur' }"
        >
          <el-select
            v-model="item.productId"
            filterable
            placeholder="请选择配料"
            class="!w-200px"
            :filter-method="getProductList"
            @change="handleProductChange(index, item.productId)"
          >
            <el-option
              v-for="dish in ProductList"
              :key="dish.id"
              :label="dish.name"
              :value="dish.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="重量"
          :prop="`mealIngreRespVOS[${index}].ingredientSpec`"
          :rules="[
            { required: true, message: '配料重量不能为空', trigger: 'blur' },
            { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
            {
              validator: validateWeight,
              trigger: ['blur', 'change'],
              index: index
            }
          ]"
        >
          <el-input
            type="number"
            v-model.number="item.ingredientSpec"
            placeholder="请输入重量"
            class="!w-200px"
            :min="0"
          >
            <template #append>{{ item.unitName || '单位' }}</template>
          </el-input>
        </el-form-item>

        <!-- 删除按钮 -->
        <el-button
          style="
            position: relative;
            top: 0px;
            margin-left: 10px;
            visibility: hidden;
            pointer-events: none;
          "
          type="danger"
          v-if="index == 0"
        >
          <Icon icon="ep:delete" />
        </el-button>
        <el-button
          v-else
          style="position: relative; top: 0px; margin-left: 10px"
          type="danger"
          @click="removeDishRow(index)"
        >
          <Icon icon="ep:delete" />
        </el-button>
      </div>
      <!-- 添加行按钮 -->
      <div style="text-align: center; margin: 10px 0">
        <el-button @click="addDishRow"><Icon icon="ep:plus" class="mr-5px" /> 添加一行</el-button>
      </div>

      <!--<el-form-item label="是否启用" prop="isActive">-->
      <!--  <el-radio-group v-model="formData.isActive">-->
      <!--    <el-radio-->
      <!--      v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"-->
      <!--      :key="dict.value"-->
      <!--      :value="dict.value"-->
      <!--    >-->
      <!--      {{ dict.label }}-->
      <!--    </el-radio>-->
      <!--  </el-radio-group>-->
      <!--</el-form-item>-->
      <el-form-item label="特殊说明" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入特殊说明" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { RecipeMealApi, RecipeMealVO } from '@/api/pplan/recipemeal'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'
import { ProductApi, ProductVO } from '@/api/erp/product/product'

/** 生产计划-餐谱菜品数据管理 表单 */
defineOptions({ name: 'RecipeMealForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  mealCode: undefined,
  mealName: undefined,
  airlineId: undefined,
  mealType: undefined,
  isActive: true,
  remarks: undefined,
  mealIngreRespVOS: [
    {
      id: undefined,
      receipeMealId: undefined,
      productId: undefined,
      ingredientSpec: undefined,
      unitName: undefined // 新增：存储当前配料的单位名称
    }
  ] // 默认一行数据
})
const formRules = reactive({
  mealName: [
    { required: true, message: '菜品名称不能为空', trigger: 'blur' },
    {
      type: 'string', // 限定为字符串类型（确保长度校验针对字符数）
      max: 32, // 最大长度为32个字符
      message: '菜品名称长度不能超过32个字符',
      trigger: ['blur', 'change']
    }
  ],
  airlineId: [{ required: true, message: '所属航空公司不能为空', trigger: 'change' }],
  mealType: [{ required: true, message: '菜品类型不能为空', trigger: 'change' }]
  // isActive: [{ required: true, message: '是否启用不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// 新增：备份完整的产品列表
const productAllList = ref<ProductVO[]>([])

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 先加载完整的产品列表
  await loadAllProducts()
  // 初始化显示列表
  await getProductList('')

  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据并补全已选配料
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RecipeMealApi.getRecipeMeal(id)
      // 确保已选配料在列表中
      await getProductList('')
      // 为已有的配料设置单位名称
      formData.value.mealIngreRespVOS.forEach((item) => {
        if (item.productId) {
          const product = productAllList.value.find((p) => p.id === item.productId)
          if (product) {
            item.unitName = product.unitName
          }
        }
      })
    } finally {
      formLoading.value = false
      if (!formData.value.mealIngreRespVOS) {
        formData.value.mealIngreRespVOS = []
      }
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 新增：加载完整的产品列表（仅加载一次） */
const loadAllProducts = async () => {
  if (productAllList.value.length > 0) return productAllList.value
  const data = await ProductApi.getProductSimpleList()
  productAllList.value = data
  return data
}

/** 获取单位列表 */
const ProductUnitList = ref<ProductUnitVO[]>([]) // 菜品列表
const getProductUnitList = async () => {
  try {
    const data = await ProductUnitApi.getProductUnitSimpleList()
    ProductUnitList.value = data
  } finally {
  }
}

/** 修改：获取配料列表（确保已选配料在列表中） */
const ProductList = ref<ProductVO[]>([]) // 配料列表（显示用）
const getProductList = async (query?: string) => {
  // 确保已加载完整产品列表
  await loadAllProducts()

  // 1. 获取所有已选的产品ID
  const selectedProductIds = formData.value.mealIngreRespVOS
    .map((item) => item.productId)
    .filter(Boolean)

  // 2. 筛选已选的产品
  const selectedProducts = selectedProductIds
    .map((id) => productAllList.value.find((product) => product.id === id))
    .filter(Boolean)

  // 3. 根据查询条件过滤数据
  let filteredProducts: ProductVO[] = []
  if (!query) {
    // 无查询时：取前200条
    filteredProducts = [...productAllList.value].slice(0, 200)
  } else {
    // 有查询时：按名称过滤
    filteredProducts = productAllList.value.filter((product) =>
      product.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 4. 合并并去重
  ProductList.value = Array.from(
    new Map([...filteredProducts, ...selectedProducts].map((item) => [item.id, item])).values()
  )

  return ProductList.value
}

/** 处理配料选择变化 */
const handleProductChange = (index: number, productId: number) => {
  if (productId) {
    const product = productAllList.value.find((p) => p.id === productId)
    if (product) {
      formData.value.mealIngreRespVOS[index].unitName = product.unitName
    }
  } else {
    formData.value.mealIngreRespVOS[index].unitName = undefined
  }
}

/** 重量自定义校验规则 */
const validateWeight = (rule: any, value: number, callback: any) => {
  const index = rule.index
  const item = formData.value.mealIngreRespVOS[index]

  // 检查是否为数字
  if (typeof value !== 'number' || isNaN(value)) {
    return callback(new Error('请输入有效的数字'))
  }

  // 检查是否大于0
  if (value <= 0) {
    return callback(new Error('配料重量需要大于0'))
  }
  callback()
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RecipeMealVO
    if (formType.value === 'create') {
      await RecipeMealApi.createRecipeMeal(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecipeMealApi.updateRecipeMeal(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    mealCode: undefined,
    mealName: undefined,
    airlineId: undefined,
    mealType: undefined,
    isActive: true,
    remarks: undefined,
    mealIngreRespVOS: [
      {
        id: undefined,
        receipeMealId: undefined,
        productId: undefined,
        ingredientSpec: undefined,
        unitName: undefined // 新增：存储当前配料的单位名称
      }
    ] // 默认一行数据
  }
  formRef.value?.resetFields()
}

const addDishRow = () => {
  formData.value.mealIngreRespVOS.push({
    id: undefined,
    receipeMealId: formData.value.id,
    productId: undefined,
    ingredientSpec: undefined,
    unitName: undefined // 新增：存储当前配料的单位名称
  })
}

/** 删除指定索引的菜品行数据 */
const removeDishRow = (index: number) => {
  formData.value.mealIngreRespVOS.splice(index, 1)
}
</script>
